<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                 label-width="78px">
<!--            <el-form-item label="标题" prop="title">-->
<!--                <el-input-->
<!--                    v-model="queryParams.title"-->
<!--                    placeholder="请输入标题"-->
<!--                    clearable-->
<!--                    @keyup.enter.native="handleQuery"-->
<!--                />-->
<!--            </el-form-item>-->
            <el-form-item label="所属村社:" prop="communityId" clearable width="120px">
                <el-select v-model="queryParams.communityId" placeholder="请选择咨询展示的村社或村" >
                    <el-option
                        v-for="community in communityList"
                        :key="community.communityId"
                        :label="community.communityName"
                        :value="community.communityId"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                    type="primary"
                    plain
                    icon="el-icon-plus"
                    size="mini"
                    @click="handleAdd"
                    v-hasPermi="['docs:ad:add']"
                >新增
                </el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="adList" @selection-change="handleSelectionChange" border>
            <el-table-column type="selection" width="55" align="center"/>
            <el-table-column label="村社名称" align="center" prop="communityName"/>
            <el-table-column label="轮播图片" align="center">
                <template slot-scope="scope">
                    <el-image :src="scope.row.url" style="width: 100px; height: 70px"></el-image>
                </template>
            </el-table-column>
            <el-table-column label="链接内容" align="center" prop="label"/>
            <el-table-column label="链接类型" align="center">
                <template slot-scope="scope">
                    <el-tag  type="warning" v-if="scope.row.type==0">信息详情</el-tag>
                    <el-tag v-if="scope.row.type==1">活动详情</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="状态" align="center" prop="status">
                <template slot-scope="scope">
                    <el-switch
                        v-model="scope.row.status"
                        active-value="0"
                        inactive-value="1"
                        @change="handleStatusChange(scope.row)"
                    ></el-switch>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-edit"
                        @click="handleUpdate(scope.row)"
                        v-hasPermi="['docs:ad:edit']"
                    >修改
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
        />

        <!-- 添加或修改轮播图片对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="100px">
                <el-form-item label="发布村社：" prop="communityId">
                    <el-select v-model="form.communityId" placeholder="请选择活动展示的村社或自然村" @change="changeCommunity" :disabled="form.communityIdShow">
                        <el-option
                            v-for="community in communityList"
                            :key="community.communityId"
                            :label="community.communityName"
                            :value="community.communityId"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="链接类型：" prop="type">
                    <el-radio-group v-model="form.type" @change="handleType">
                        <el-radio :key="type.value" :label="type.value" v-for="type in types">{{ type.label }}</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="链接内容：" prop="contentId">
                    <el-cascader ref="xzCascader" @change="cascaderChange" :key="modalKey" v-model="cas" :options="options" placeholder="请选择链接内容" style="width: 300px" size="medium" clearable></el-cascader>
                </el-form-item>

                <el-form-item label="链接图片：" prop="url">
                    <image-upload v-model="form.url" :limit="1" :fileSize="1"/>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {listAd, getAd, delAd, addAd, updateAd,changeAdStatus} from "@/api/docs/ad";
import {getArticleTree} from "@/api/docs/article";
import {getActivityTree} from "@/api/docs/activity";
import {listCommunity} from "@/api/organization/community";

export default {
    name: "Ad",
    data() {
        return {
            modalKey:0,
            cas:[],
            options:[],
            types:[{'value':0,'label':'信息详情'},{'value':1,'label':'活动详情'}],
            articles:[],
            srcList: [],
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 轮播图片表格数据
            adList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            communityList: [],
            querycommunityParams:{
                pageNum: 1,
                pageSize: 100,
                status:0
            },
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                adTitle: null,
                contentId: null,
                url: null,
                status: null,
            },
            articleVars:{
                pageSize:20,
                pageNum: 1
            },
            // 表单参数
            form: {
                type:0
            },
            // 表单校验
            rules: {
                contentId: [{required: true, message: "链接内容不能为空", trigger: "blur"}],
                url: [{required: true, message: "链接图片不能为空", trigger: "blur"}],
            }
        };
    },
    created() {
        this.getList();
        this.listCommunityOptions();
    },
    methods: {
        changeCommunity(raw) {
            console.log('changeCommunity')
            for (let communityListElement of this.communityList) { console.log(communityListElement)
                if(communityListElement.communityId==raw) {
                    this.form.communityName = communityListElement.communityName;
                    break;
                }
            }

        },
        listCommunityOptions() {
            listCommunity(this.querycommunityParams).then(resp => {
                this.communityList = resp.rows;
                this.getArticles();
            })


        },
        getArticles(){
            const communityVars = {};
            if (this.communityList.length==1) {
                communityVars.communityId = this.communityList[0].communityId;
            }
            if (this.form.type==0) {

                getArticleTree(communityVars).then(res=>{
                    this.options=res.data;
                })
            }
            else {
                getActivityTree(communityVars).then(res=>{
                    this.options = res.data
                })
            }
        },
        /** 查询轮播图片列表 */
        getList() {
            this.loading = true;
            listAd(this.queryParams).then(response => {
                this.adList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                adId: null,
                contentId: null,
                url: null,
                type: null,
                status: null,
                label:null,
                labelIds:null
            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.adId)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = "添加轮播图片";
            this.form.type=0;
            this.form.contentId=[]
            this.modalKey++;
        },
        handleType(label) {
            this.form.type = label;
            this.getArticles();
        },
        cascaderChange(raw){
            if (raw.length>0) {
                const obj =  this.$refs['xzCascader'].getCheckedNodes(true)[0].pathLabels;
                this.form.label = obj.join('/');
                this.form.labelIds = raw.join(',');
                var split = raw.toString().split(',');
                this.form.contentId = split[split.length-1];
            }
            else {
                this.form.contentId ='';
                this.form.label = '';
                this.form.labelIds = '';
            }


        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            const adId = row.adId || this.ids
            getAd(adId).then(response => {
                this.form = response.data;
                this.getArticles();
                this.open = true;
                this.title = "修改轮播图片";
                this.cas = this.form.labelIds.split(",")
                console.log(this.cas)
                this.modalKey++;
            });
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    if (this.form.adId != null) {
                        updateAd(this.form).then(response => {
                            this.$modal.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                        });
                    } else {
                        addAd(this.form).then(response => {
                            this.$modal.msgSuccess("新增成功");
                            this.open = false;
                            this.getList();
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const adIds = row.adId || this.ids;
            this.$modal.confirm('是否确认删除轮播图片编号为' + adIds + '"的数据项？').then(function () {
                return delAd(adIds);
            }).then(() => {
                this.getList();
                this.$modal.msgSuccess("删除成功");
            }).catch(() => {
            });
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download('docs/ad/export', {
                ...this.queryParams
            }, `ad_${new Date().getTime()}.xlsx`)
        },
        handleStatusChange(row) {
            let text = row.status === "0" ? "启用" : "禁用";
            this.$modal.confirm('确认要' + text  + row.label + '这个链接内容嘛？').then(function() {
                return changeAdStatus(row.adId, row.status);
            }).then(() => {
                this.$modal.msgSuccess(text + "成功");
            }).catch(function() {
                row.status = row.status === "0" ? "1" : "0";
            });
        },
    }
};
</script>
